package com.justauth.controller;

import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@RequestMapping("/oauth")
public class RestAuthController {

    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId("e930586e833a7a3b5740bf672ca8dfde73ceaa1b428c650afc5550e737756952")
                .clientSecret("737186b06c8cf71ae255f5a3df395cc5b673d5941a0cf9541a804b7b36f0ed07")
                .redirectUri("http://3hzytb.natappfree.cc/oauth/callback")
                .build());
    }

    /**
     * Gitee授权登录
     */
    @GetMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }

    /**
     * 回调地址
     */
    @GetMapping("/callback")
    public String login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        AuthResponse<AuthUser> response = authRequest.login(callback);
        if (response.ok()) {
            AuthUser user = response.getData();
            System.out.println("获取到的用户信息：" + user.getAvatar());
            return "登录成功";
        }
        return "登录失败";
    }

}
